﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Collections.Generic;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace ipi.MCC.Controls
{

	public class PeoplePicker : System.Web.UI.UserControl
	{
		protected PeopleEditor pePeople;
		private string _CommaSeparated;

		public bool IsValid
		{
			get
			{			
				this.pePeople.Validate();
				return this.pePeople.IsValid;				 
			}

		}

		public bool AllowTypeIn
		{
			set
			{
				if (ViewState["_AllowTypeIn"] == null)
				{
					ViewState.Add("_AllowTypeIn", value);
				}
				else
				{
					ViewState["_AllowTypeIn"] = value;
				}
			}

			get
			{
				if (ViewState["_AllowTypeIn"] == null)
				{
					return true;
				}
				else
				{
					return (bool)ViewState["_AllowTypeIn"];
				}
			}
		}
	
		public bool AllowEmpty
		{
			set
			{
				if(ViewState["_AllowEmpty"] == null)
				{
					ViewState.Add("_AllowEmpty", value);
				}
				else
				{
					ViewState["_AllowEmpty"] = value;
				}
			}

			get
			{
				if (ViewState["_AllowEmpty"] == null)
				{
					return true;
				}
				else
				{
					return (bool)ViewState["_AllowEmpty"];
				}
			}
		}
		
		public bool MultiSelect
		{
			set
			{
				if(ViewState["_MultiSelect"] == null)
				{
					ViewState.Add("_MultiSelect", value);
				}
				else
				{
					ViewState["_MultiSelect"] = value;
				}
			}

			get
			{
				if (ViewState["_MultiSelect"] == null)
				{
					return false;
				}
				else
				{
					return (bool)ViewState["_MultiSelect"];
				}
			}
		}
		
		public void SetValue(string sCommaSeparatedValue)
		{
			_CommaSeparated = sCommaSeparatedValue;
		}

		public void SetValue(SPFieldUserValue FieldValue)
		{
			_CommaSeparated = FieldValue.User.LoginName;
		}

		public void SetValue(SPFieldUserValueCollection FieldValue)
		{
			string sCommaSeparated = "";
			string sSeparator = "";
			foreach (SPFieldUserValue fuvCurrent in FieldValue)
			{
				sCommaSeparated += sSeparator + fuvCurrent.User.LoginName;
				sSeparator = ", ";
			}

			_CommaSeparated = sCommaSeparated;
		}

        public SPPrincipal GetUserData()
        {
            if (pePeople.ResolvedEntities.Count > 0)
            {
                SPWeb webCurrent = SPContext.Current.Web;

                PickerEntity current = (PickerEntity)pePeople.ResolvedEntities[0];

                SPPrincipal principal = null;

                switch (Convert.ToString(current.EntityData["PrincipalType"]))
                {
                    case "User":
                        try 
                        {	        
                            // User suchen. Wenn nicht vorhanden kommt eine Exception, leider kein NLLL
                    		principal = webCurrent.AllUsers[current.Key];
                        }
                        catch (Exception)
                        {
                            // User hinzufügen
                    		setPermission(current);
                            principal = webCurrent.AllUsers[current.Key];
                        }
                        break;
                                                 
                    case "SecurityGroup":
                        try
                        {
                            // Security Gruppe (AD) suchen. Wenn nicht vorhanden kommt eine Exception, leider kein NLLL
                            principal = webCurrent.AllUsers[current.Key];
                        }
                        catch (Exception)
                        {
                            // Security Gruppe (AD) hinzufügen
                            setPermission(current);
                            principal = webCurrent.AllUsers[current.Key];
                        }
                        break;
                    case "SharePointGroup":
                        principal = webCurrent.Groups[current.Key];
                        break;
                }
                return principal;                            
            }
            else
            {
                return null;
            }
        }

        private void setPermission(PickerEntity current)
        {
            SPWeb webCurrent = SPContext.Current.Web;

            //List<string> list = new List<string>();

            //SPRoleDefinitionBindingCollection rDefBinColl = new SPRoleDefinitionBindingCollection();
            //rDefBinColl.Add(webCurrent.RoleDefinitions.GetById(1073741826)); // Lese-Berechtigungen

            //SPRoleAssignmentCollection roleAssignments = webCurrent.RoleAssignments;
            SPGroup spgVisitor = webCurrent.AssociatedVisitorGroup;

            spgVisitor.AddUser(current.Key, (string)current.EntityData["Email"], current.DisplayText, string.Empty);
            spgVisitor.Update();

            /*if (!current.EntityData.ContainsKey("SPGroupID")) // Wenn es keine SP Gruppe ist.
            {
                SPRoleAssignment roleAssignment = new SPRoleAssignment(current.Key, (string)current.EntityData["Email"], current.DisplayText, string.Empty);

                roleAssignment.ImportRoleDefinitionBindings(rDefBinColl);
                roleAssignments.Add(roleAssignment);

            }*/

            if (webCurrent != null)
                webCurrent.Dispose();
        }

        
        public string GetValue()
		{
			string sPeopleList = "";

			string sPeopleListSeperator = "";
			foreach (PickerEntity currentEntity in this.pePeople.ResolvedEntities)
			{                
                if (currentEntity.EntityData["DisplayName"] == null)
				{
					throw(new Exception("User " + currentEntity.DisplayText + " can not be used, because no 'DisplayName' found!"));
				}
				else
				{
					sPeopleList += sPeopleListSeperator +
												 currentEntity.EntityData["SPUserID"].ToString() +
												 ";#" +
												 currentEntity.EntityData["DisplayName"];

					sPeopleListSeperator = ";#";
				}
			}

			return sPeopleList;
		}

		protected override void Render(HtmlTextWriter writer)
		{
			// TODO: add custom rendering code here.
			// writer.Write("Output HTML");
			EnsureChildControls();

			// The appropriate child control will render based on what was added to the collection
			try
			{
				this.pePeople.RenderControl(writer);
				
				//RenderChildren(writer);
			}
			catch (System.Exception ex)
			{
				writer.WriteLine("The following error occurred in this Web Part.  Please contact your administrator for further assistance. \n" + ex.Message);
			}
		}
		
		protected override void CreateChildControls()
		{
			base.CreateChildControls();

			this.Controls.Clear();

			this.pePeople = new PeopleEditor();
			this.pePeople.ID = "pePeople" + pePeople.ClientID;
			this.pePeople.Visible = true;
			this.pePeople.Enabled = true;
			this.pePeople.ShowButtons = true;
			this.pePeople.EnableBrowse = true;

			this.pePeople.MultiSelect = MultiSelect;
			this.pePeople.AllowEmpty = AllowEmpty;
			this.pePeople.AllowTypeIn = AllowTypeIn;
            this.pePeople.SelectionSet = "User,SPGroup,SecGroup";

			if (!string.IsNullOrEmpty(_CommaSeparated))
			{
				this.pePeople.CommaSeparatedAccounts = _CommaSeparated;
			}

			this.Controls.Add(pePeople);
		}
	}
}
